package com.yinhe.music.yhmusic.widget;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

import com.yinhe.music.yhmusic.R;

/**
 * @author 何晓华
 */
public class LoadingView extends LinearLayout implements View.OnClickListener {
    private View error;
    private View loading;
    private State state;

    private OnRetryListener listener;

    public interface OnRetryListener {
        /**
         * 重新请求
         */
        void onRetry();
    }

    public enum State {
        /**
         *正在加载
         */
        LOADING,
        /**
         * 加载错误
         */
        ERROR,
        /**
         * 加载完成
         */
        DONE
    }

    public LoadingView(@NonNull Context context) {
        super(context);
        initializeView(context);
    }

    public LoadingView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initializeView(context);
    }

    public LoadingView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initializeView(context);
    }

    private void initializeView(Context context) {
        LayoutInflater.from(context).inflate(R.layout.include_loading, this);
        loading = findViewById(R.id.loading);
        error = findViewById(R.id.load_fail);
        setOnClickListener(this);
        notifyDataChanged(State.DONE);
    }

    public void notifyDataChanged(State state) {
        this.state = state;
        switch (state) {
            case LOADING:
                setVisibility(View.VISIBLE);
                loading.setVisibility(View.VISIBLE);
                error.setVisibility(View.GONE);
                break;
            case ERROR:
                setVisibility(View.VISIBLE);
                loading.setVisibility(View.GONE);
                error.setVisibility(View.VISIBLE);
                break;
            case DONE:
                setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    public void setOnRetryListener(OnRetryListener listener) {
        this.listener = listener;
    }

    @Override
    public void onClick(View v) {
        if (listener != null && state == State.ERROR) {
            listener.onRetry();
        }
    }


}
